import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
  
  @Catch()
  export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: unknown, host: ArgumentsHost) {
      const ctx = host.switchToHttp();
      const response = ctx.getResponse();
      const request = ctx.getRequest();
  
      let status = HttpStatus.INTERNAL_SERVER_ERROR;
      let message = '发生错误';
      let sqlMessage: unknown;
  
      if (exception instanceof HttpException) {
        status = exception.getStatus();
        message = exception.message;
      } else if (exception instanceof Error) {
        if ('sqlMessage' in exception) {
          sqlMessage = exception.sqlMessage;
        }
        message = exception.message || message;
      }
  
      const msgLog = {
        status,
        message,
        path: request.url,
        method: request.method,
        timestamp: new Date().toLocaleString(),
        sqlMessage: sqlMessage || '无SQL错误信息',
      };
  
      response.status(status).json(msgLog);
    }
  }